<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getDepartments, 
  createDepartment, 
  updateDepartment, 
  deleteDepartment,
  getDepartmentTree,
  getDepartmentOptions,
  activateDepartment
} from '@/api/index.js';
import useUserInfoStore from '@/store/user.js';

// 添加防抖功能
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(null, args), delay)
  }
}

const store = useUserInfoStore();
const loading = ref(false);
const departments = ref([]);
const allDepartments = ref([]); // 缓存所有部门数据
const departmentTree = ref([]);
const departmentOptions = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchText = ref('');

// 对话框控制
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);

// 表单数据
const form = reactive({
  id: null,
  name: '',
  description: '',
  parent: null,
  manager: null
});

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { max: 100, message: '部门名称不能超过100个字符', trigger: 'blur' }
  ]
});

// 检查权限
const hasManagePermission = () => {
  return store.userInfo?.user_type === 'ADMIN' || store.userInfo?.user_type === 'MANAGER';
};

// 获取部门列表
const fetchDepartments = async (forceRefresh = false) => {
  try {
    loading.value = true;
    
    // 如果没有缓存数据或强制刷新，则从后端获取数据
    if (allDepartments.value.length === 0 || forceRefresh) {
      const params = {};
      const res = await getDepartments(params);
      if (res.status === 200) {
        allDepartments.value = res.data || [];
      } else {
        ElMessage.error(res.msg || '获取部门列表失败');
        return;
      }
    }
    
    // 过滤搜索结果 - 只搜索部门名称
    let filteredDepartments = allDepartments.value;
    if (searchText.value.trim()) {
      filteredDepartments = allDepartments.value.filter(dept => 
        dept.name.includes(searchText.value.trim())
      );
    }
    
    // 前端分页处理
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    departments.value = filteredDepartments.slice(startIndex, endIndex);
    total.value = filteredDepartments.length;
    
  } catch (error) {
    console.error('获取部门列表出错:', error);
    ElMessage.error('网络错误，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 获取部门树形结构
const fetchDepartmentTree = async () => {
  try {
    const res = await getDepartmentTree();
    if (res.status === 200) {
      departmentTree.value = res.data;
    }
  } catch (error) {
    console.error('获取部门树失败:', error);
  }
};

// 获取部门选项
const fetchDepartmentOptions = async () => {
  try {
    const res = await getDepartmentOptions();
    if (res.status === 200) {
      departmentOptions.value = res.data;
    }
  } catch (error) {
    console.error('获取部门选项失败:', error);
  }
};

// 添加防抖搜索
const debouncedSearch = debounce(() => {
  currentPage.value = 1
  fetchDepartments()
}, 500)

const handleInputSearch = () => {
  debouncedSearch()
}

// 搜索部门
const handleSearch = () => {
  currentPage.value = 1;
  fetchDepartments();
};

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchDepartments();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchDepartments();
};

// 打开新增对话框
const openCreateDialog = () => {
  if (!hasManagePermission()) {
    ElMessage.error('您没有权限执行此操作');
    return;
  }
  
  dialogTitle.value = '新增部门';
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  if (!hasManagePermission()) {
    ElMessage.error('您没有权限执行此操作');
    return;
  }
  
  dialogTitle.value = '编辑部门';
  isEdit.value = true;
  Object.assign(form, {
    id: row.id,
    name: row.name,
    description: row.description || '',
    parent: row.parent,
    manager: row.manager
  });
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    name: '',
    description: '',
    parent: null,
    manager: null
  });
};

// 表单引用
const formRef = ref(null);

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          name: form.name,
          description: form.description,
          parent: form.parent,
          manager: form.manager
        };
        
        let res;
        if (isEdit.value) {
          res = await updateDepartment(form.id, data);
        } else {
          res = await createDepartment(data);
        }
        
        if (res.status === 200 || res.status === 201) {
          ElMessage.success(res.msg || '操作成功');
          dialogVisible.value = false;
          fetchDepartments(true); // 强制刷新
          fetchDepartmentTree();
          fetchDepartmentOptions();
        } else {
          ElMessage.error(res.msg || '操作失败');
        }
      } catch (error) {
        console.error('提交表单出错:', error);
        ElMessage.error('网络错误，请稍后再试');
      }
    }
  });
};

// 激活/禁用部门
const handleActivate = async (row) => {
  if (!hasManagePermission()) {
    ElMessage.error('您没有权限执行此操作');
    return;
  }
  
  const action = row.is_active ? '禁用' : '激活';
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}部门"${row.name}"吗？`,
      `确认${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const res = await activateDepartment(row.id, { is_active: !row.is_active });
    if (res.status === 200) {
      ElMessage.success(res.msg || `${action}成功`);
      fetchDepartments(true); // 强制刷新
      fetchDepartmentTree();
      fetchDepartmentOptions();
    } else {
      ElMessage.error(res.msg || `${action}失败`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}部门出错:`, error);
      ElMessage.error('网络错误，请稍后再试');
    }
  }
};

// 删除部门
const handleDelete = async (row) => {
  if (!hasManagePermission()) {
    ElMessage.error('您没有权限执行此操作');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除部门"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const res = await deleteDepartment(row.id);
    if (res.status === 200) {
      ElMessage.success('删除成功');
      fetchDepartments(true); // 强制刷新
      fetchDepartmentTree();
      fetchDepartmentOptions();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除部门出错:', error);
      ElMessage.error('网络错误，请稍后再试');
    }
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchDepartments();
  fetchDepartmentTree();
  fetchDepartmentOptions();
});
</script>

<template>
  <div class="department-management">
    <!-- 权限检查 -->
    <div v-if="!hasManagePermission()" class="no-permission">
      <el-result icon="warning" title="权限不足" sub-title="您没有权限管理部门信息">
        <template #extra>
          <el-button type="primary" @click="$router.back()">返回</el-button>
        </template>
      </el-result>
    </div>

    <!-- 部门管理界面 -->
    <div v-else class="management-container">
      <el-card class="management-card">
        <template #header>
          <div class="card-header">
            <h2>部门管理</h2>
            <div class="header-actions">
              <div class="search-container">
                <el-input
                  v-model="searchText"
                  placeholder="搜索部门名称"
                  clearable
                  @input="handleInputSearch"
                  style="width: 200px; margin-right: 10px;"
                />
              </div>
              <el-button type="success" @click="openCreateDialog">新增部门</el-button>
            </div>
          </div>
        </template>

        <!-- 部门列表表格 -->
        <el-table :data="departments" v-loading="loading" stripe row-key="id">
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="name" label="部门名称" />
          <el-table-column prop="full_name" label="完整路径" />
          <el-table-column prop="parent_name" label="上级部门">
            <template #default="scope">
              <span>{{ scope.row.parent_name || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="manager_name" label="部门负责人">
            <template #default="scope">
              <span>{{ scope.row.manager_name || '未设置' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="children_count" label="子部门数" width="100" />
          <el-table-column prop="description" label="部门描述" show-overflow-tooltip />
          <el-table-column label="状态" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
                {{ scope.row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="160">
            <template #default="scope">
              {{ scope.row.created_time ? new Date(scope.row.created_time).toLocaleString() : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="openEditDialog(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                :type="scope.row.is_active ? 'warning' : 'success'"
                size="small"
                @click="handleActivate(scope.row)"
              >
                {{ scope.row.is_active ? '禁用' : '激活' }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑部门对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
        
        <el-form-item label="上级部门">
          <el-select
            v-model="form.parent"
            placeholder="请选择上级部门"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dept in departmentOptions"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
              :disabled="isEdit && dept.value === form.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="部门描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入部门描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.department-management {
  padding: 20px;
  
  .no-permission {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }
  
  .management-container {
    max-width: 1400px;
    margin: 0 auto;
  }
  
  .management-card {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h2 {
        margin: 0;
        font-size: 20px;
        color: #333;
      }
      
      .header-actions {
        display: flex;
        align-items: center;
        gap: 10px;
        
        .search-container {
          display: flex;
          align-items: center;
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  
  .dialog-footer {
    text-align: right;
  }
}
</style>